import React from 'react';
import {connect} from 'dva';
import {Link, browserHistory} from 'dva/router';
import {Table, Row, Col, Form, Input, Icon, InputNumber, Radio, DatePicker, Select, Upload, Button, Switch, Modal, Popconfirm, Tabs, message} from 'antd';
const R = require('ramda');
const dateFormat = 'YYYY-MM-DD';
const { RangePicker } = DatePicker;
import RightContacts from "../../../utils/RightConstants";
import EditCustomer from '../../../components/customer/components/EditCustomer';
import BizParams from '../../../components/commons/BizParams'
import CustomerDetail from '../../../components/customer/components/CustomerDetail';
import RightBox from "../../../components/commons/RightBox";
import Constants from "../../../utils/Constants";


const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
export default connect(({customerManage, businessAgreement}) => ({customerManage, businessAgreement}))(
    Form.create()(class mpCstManage extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                open: false,
            }
        }

        componentDidMount() {
            this.props.dispatch({
                type: 'customerManage/queryCustomerManageList',
                payload: {
                    status: 1,
                    businessType: Constants.NUMBER_TWO
                }
            });
        }

        handleAdd = () => {
            this.setState({open: true});
        }

        collectSearchCondition = () => {
            let conditions = this.props.form.getFieldsValue();
            conditions.page = this.props.customerManage.page;
            return conditions;
        }

        handleResetFields = () => {
            if(this.editCustomer)this.editCustomer.handleResetFields();
        }

        handleCancel = (flag) => {
            if(flag){
                this.handleResetFields();
            }
            this.setState({ open: false});
        }

        onView = (record) => {
            this.handleOpenDetail(record, true,  {}, "1", true);
        }

        onEdit = (record) => {
            this.handleOpenDetail(record, false, {}, "1", false);
        }

        handleOpenDetail = (record, customerDisabled, searchConditions, tabActiveKey, editCustomerDisable) => {
            this.props.dispatch({type: 'customerManage/getCustomerById', payload: {id: record.id, isApproval: true}});
            this.props.dispatch({type: 'customerManage/getLinkmanList', payload: {cstId: record.id, page :  this.props.customerManage.linkmanPage}});//查询联系人列表
            this.props.dispatch({type: 'customerManage/getAgencyagreementList', payload: {id: record.id, page: this.props.customerManage.agencyagreementPage}});
            this.props.dispatch({type: 'businessAgreement/getAgreementlList', payload: {cstId: record.id, status: 1}});
            this.props.dispatch({type: 'customerManage/getListByCstIdForPage', payload: {cstId: record.id, page: this.props.customerManage.marketInfoPage}});
            // this.props.dispatch({type: 'customerManage/getManagerList', payload: {}});
            // this.props.dispatch({type: 'customerManage/getApprovaList', payload: {cstId: record.id}});

            this.refs.customerDetail.handleOpen(customerDisabled, searchConditions, tabActiveKey, record.id, editCustomerDisable, "customerManage");
        }

        handleSearch = () => {
            let values = this.props.form.getFieldsValue();
            let newPage = this.props.customerManage.page;
            newPage.page = 1;
            let time=values.time;


            this.props.dispatch({
                type: 'customerManage/queryCustomerManageList',
                payload: {
                    customerNO: values.customerNO,
                    cstName: values.cstName,
                    cstType: values.cstType,
                    cstManage: values.cstManage,
                    cstWaiter: values.cstWaiter,
                    status: 1,
                    businessType: Constants.NUMBER_TWO,
                    page: newPage,
                    beginTime:R.isNil(time)||R.isEmpty(time)?null:time[0].format(dateFormat),
                    endTime:R.isNil(time)||R.isEmpty(time)?null:time[1].format(dateFormat),
                }
            });
        };

        handleConfirm = () => {
            if(this.editCustomer){
                if(this.editCustomer.checkCustomerInfo(this.props.dispatch,this.onSuccess) ==  true){
                    this.handleSearch();
                }

            }



        };

        onSuccess=()=>{
            this.handleSearch();
            this.handleCancel();
            this.handleResetFields();
        };


        columns = [
            {title: '客户编码', dataIndex: 'customerno', key: 'customerno'},

            // {title: '代理协议号', dataIndex: 'companyna', key: 'companyna', render(record) {
            //     return ("xx");
            // }},

            {title: '客户名称', dataIndex: 'companyname', key: 'companyname',},

            {title: '客户类型', render(record) {
                    if(R.isNil(record.companytypeName) || R.isEmpty(record.companytypeName)){
                        return "未分配"
                    }else{
                        return record.companytypeName;
                    }
                }},

            {title: '业务经理', render(record) {
                    if(R.isNil(record.managerName) || R.isEmpty(record.managerName)){
                        return "未分配";
                    }else{
                        return record.managerName;
                    }
                }},

            {title: '跟单经理', render(record) {
                    if(R.isNil(record.waiterName) || R.isEmpty(record.waiterName)){
                        return "未分配";
                    }else{
                        return record.waiterName;
                    }
                }},

            {title: '创建时间', dataIndex: 'createtime', key: 'createtime'},

            {title: '操作', key: 'key_oprator',

                render: (text, record, index) => {
                    let deleteButton =
                        <RightBox resource={RightContacts.MPCUSTOMER.MPCUSTOMER_MANAGE_MPCUSTOMER_DELETE} >
                            <Popconfirm placement="leftTop" title={'数据删除后将不可以恢复，是否继续删除？'} onConfirm={() => {
                                if(record.csttype === '1'){
                                    message.info("当前是会员客户，不允许删除！");
                                    return;
                                }
                                this.props.dispatch({
                                    type: 'customerManage/deleteCustomerById',
                                    payload: {
                                        id : record.id,
                                        onSuccess:()=>{
                                            this.handleSearch();
                                        }
                                    }
                                });
                            }} okText="是" cancelText="否">
                                <a href="#">删除</a>

                            </Popconfirm></RightBox>;


                    let editButton=<RightBox resource={RightContacts.MPCUSTOMER.MPCUSTOMER_MANAGE_MPCUSTOMER_EDIT} split={false}>
                        {record.status === "1" || record.status === "3" ?
                            <span><a href="#" onClick={this.onEdit.bind(this, record)}>编辑</a> <span className="ant-divider"/></span>: ''}

                    </RightBox>;



                    deleteButton = record.status === "1" || record.status === "3" ? deleteButton : "";
                    let split = deleteButton === "" ? "" : <span className="ant-divider"/>;
                    return (
                        <span>
                        {record.status === "1" || record.status === "3" ? editButton:''}
                            {deleteButton}

                            {record.status === "2" || record.status === "4" || record.status === "5" ?
                                <a href="#" onClick={this.onView.bind(this, record)}>查看</a>: ''}
                    </span>
                    );
                }
            }
        ];

        render () {
            let dataSouce = R.isNil(this.props.customerManage.dataSource) ? {} : this.props.customerManage.dataSource;
            let formItemLayout = {labelCol: {span: 6}, wrapperCol: {span: 18}};
            const { getFieldDecorator } = this.props.form;
            let values = this.props.form.getFieldsValue();
            let time=values.time;
            let pagination = {
                showTotal: total => `共 ${total} 条数据`,
                pageSize: this.props.customerManage.page.size,
                total: this.props.customerManage.page.totalRow,
                showSizeChanger: true,
                current: this.props.customerManage.page.page,
                onShowSizeChange: (current, size) => {
                    let newPage = this.props.customerManage.page;
                    newPage.size = size;
                    newPage.page = 1;
                    this.props.dispatch({
                        type: 'customerManage/queryCustomerManageList',
                        payload: {
                            customerNO: values.customerNO,
                            cstName: values.cstName,
                            cstType: values.cstType,
                            cstManage: values.cstManage,
                            cstWaiter: values.cstWaiter,
                            status: 1,
                            businessType: Constants.NUMBER_TWO,
                            page: newPage,
                            beginTime:R.isNil(time)||R.isEmpty(time)?null:time[0].format(dateFormat),
                            endTime:R.isNil(time)||R.isEmpty(time)?null:time[1].format(dateFormat),
                        }
                    });
                },
                onChange: (pageNumber, pageSize) => {
                    let newPage = this.props.customerManage.page;
                    newPage.page = pageNumber;
                    this.props.dispatch({
                        type: 'customerManage/queryCustomerManageList',
                        payload: {
                            customerNO: values.customerNO,
                            cstName: values.cstName,
                            cstType: values.cstType,
                            cstManage: values.cstManage,
                            cstWaiter: values.cstWaiter,
                            status: 1,
                            businessType: Constants.NUMBER_TWO,
                            page: newPage,
                            beginTime:R.isNil(time)||R.isEmpty(time)?null:time[0].format(dateFormat),
                            endTime:R.isNil(time)||R.isEmpty(time)?null:time[1].format(dateFormat),
                        }
                    });
                }
            }
            return (
                <div>

                    <Row>
                        <Col span={7}><FormItem {...formItemLayout} label={'客户代码'}>{getFieldDecorator('customerNO')(<Input/>)}</FormItem></Col>
                        <Col span={7}><FormItem {...formItemLayout} label={'客户名称'}>{getFieldDecorator('cstName')(<Input/>)}</FormItem></Col>
                    </Row>
                    <Row>
                        <Col span={7}><FormItem {...formItemLayout} label={'业务经理'}>{getFieldDecorator('cstManage')(<Input/>)}</FormItem></Col>
                        <Col span={7}><FormItem {...formItemLayout} label={'跟单经理'}>{getFieldDecorator('cstWaiter')(<Input/>)}</FormItem></Col>
                    </Row>
                    <Row>
                        <Col span={7}><FormItem {...formItemLayout} label={'客户类型'}>
                            {getFieldDecorator('cstType')(
                                <BizParams sprCode={"cstType"} style={{width:'100%'}} all={true}/>
                            )}
                        </FormItem></Col>
                        <Col span={7}>
                            <FormItem {...formItemLayout} label={'创建时间'}>
                                {getFieldDecorator('time', {})(
                                    <RangePicker
                                        style={{width: '100%'}}
                                        showTime={{ format: 'YYYY-MM-DD' }}
                                        format="YYYY-MM-DD"
                                        placeholder={['开始时间', '结束时间']}
                                    />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={7} style={{float: 'right'}}>
                            <Button type="primary" icon="search" style={{marginRight: 5}} onClick={this.handleSearch.bind(this)}>查询</Button>
                            <RightBox resource={RightContacts.MPCUSTOMER.MPCUSTOMER_MANAGE_MPCUSTOMER_ADD}><Button type="primary" icon="plus" style={{marginRight: 5}} onClick={this.handleAdd.bind(this)}>添加客户</Button></RightBox>

                        </Col>
                    </Row>

                    <Table dataSource={this.props.customerManage.list} columns={this.columns} bordered={true}
                           size={'middle'} pagination={pagination}/>

                    <CustomerDetail ref={"customerDetail"} cstId={dataSouce.cstid} {...this.props.customerManage}
                                    businessAgreement={this.props.businessAgreement} dispatch={this.props.dispatch}
                                    handleSearch = {this.handleSearch}/>

                    <Modal maskClosable={false} visible={this.state.open} title={"编辑客户"} width={800}
                           wrapClassName="vertical-center-modal" onCancel={this.handleCancel} onOk={this.handleConfirm}>
                        <EditCustomer wrappedComponentRef={(inst) => this.editCustomer = inst} type={"add"} businessType={"2"}
                                      handleSearch = {this.handleSearch}/>
                    </Modal>
                </div>
            )
        }
    })

)
